<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools style="margin-bottom:20px">
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'aa'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card>
        <!-- :default-sort="{prop: 'workNumber'}"    sortable -->
        <el-table :data="list" :default-sort="{prop:'timeOfEntry'}" style="margin-bottom:20px">
          <el-table-column
            label="序号"
            type="index"
            :index="(index)=>{return (index+1) + (page-1)*size }"
          />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          background
          :total="total"
          :page-size="size"
          :current-page.sync="curPage"
          @current-change="hCurrentChange"
        />
      </el-card>

    </div>
    <!-- 弹层 -->
    <el-dialog
      title="添加员工"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <AddorEdit
        ref="EmpDialog"
        @close="showDialog=false"
        @update-employee="hUpdateEmpolyee"
      />
    </el-dialog>
    <!-- 角色分配 -->
    <el-dialog
      title="角色分配"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <Assignpole
        ref="assign"
        :cur-id="curId"
        @cancel="showDialogRole=false"
      />
    </el-dialog>
  </div>
</template>

<script>
import AddorEdit from './empDialog.vue'
import Assignpole from './assignRole.vue'
import Type from '@/constant/employees'
const hireType = Type.hireType
const hireTypenum = hireType.reduce((acc, item) => {
  return { ...acc, [item.id]: item.value
  }
}, {})
import { getEmployeeList, deleteEmployeeList } from '../../api/employees'
export default {
  components: {
    AddorEdit, Assignpole
  },
  data() {
    return {
      list: [], // 员工
      total: 0,
      page: 1, // 当前页码
      size: 4, // 每页几条
      showDialog: false, // 弹层
      showDialogRole: false,
      curPage: 1,
      curId: '' // 当前的员工编号
    }
  },
  created() {
    this.loadEmployee()
  },
  methods: {
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      let data = []
      // 找到第一个元素
      const first = list[0]
      if (!first) {
        return { header, data }
      }
      header = Object.keys(first).map(kay => {
        return map[kay]
      })
      data = list.map(obj => {
        const key = obj['formOfEmployment']
        obj['formOfEmployment'] = hireTypenum[key]
        return Object.values(obj)
      })
      return { header, data }
    },
    // excel导出
    hExport() {
      import('../../../src/vendor/Export2Excel').then(async excel => {
        const res = await getEmployeeList(this.page, this.size)
        const list = res.data.rows
        console.log('从后端获取的数据', list)
        const { header, data } = this.formatData(list)
        console.log('1111111111111111111111111111111', header, data)
        excel.export_json_to_excel({
          header: header, // 表头 必填
          data: data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 格式化
    formatEmployment(id) {
      // const item = hireType.find(item => item.id === num)
      // if (item) {
      //   return item.value
      // } else {
      //   return '不太确定'
      // }
      return hireTypenum[id]
    },
    // 获取员工列表
    async loadEmployee() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log('获取员工列表', res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
      }
    },
    hCurrentChange(curPage) {
      // 更新页码
      this.page = curPage
      this.loadEmployee()
    },
    // 删除员工列表
    hDel(id) {
      this.$confirm('确认是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.doDele(id)
      }).catch(() => {

      })
    },
    async doDele(id) {
      try {
        const res = await deleteEmployeeList(id)
        console.log(res)
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.page--
          if (this.page < 0) {
            this.page = 1
          }
        }
        this.loadEmployee()
      } catch (err) {
        this.$message.error('删除失败')
        console.log(err)
      }
    },
    hUpdateEmpolyee() {
      this.showDialog = false
      if (this.total % this.size === 0) {
        this.page = (this.total / this.size) + 1
      } else {
        // 最后一页的页码
        this.page = Math.floor(this.total / this.size) + 1
      }
      this.loadEmployee()
    },
    // 清理表单
    hClose() {
      this.$refs.EmpDialog.resetFrom()
    },
    hAssignRole(id) {
      this.curId = id
      this.showDialogRole = true
      this.$nextTick(() => {
        this.$refs.assign.loadUserDetailById()
      })
    }

  }
}
</script>

<style lang="less" scoped>

</style>
